package com.daka.tools;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public final class DateUtil
{

    static Logger log = LoggerFactory.getLogger(DateUtil.class);
    private static transient int gregorianCutoverYear = 1582;

    /**
     * 闰年中每月天数
     */
    private static final int[] DAYS_P_MONTH_LY = {
            31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };

    /**
     * 非闰年中每月天数
     */
    private static final int[] DAYS_P_MONTH_CY = {
            31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };

    /**
     * 代表数组里的年、月、日
     */
    private static final int Y = 0, M = 1, D = 2;

    public final static int SUNDAY = 1;

    /**
     */
    public final static int MONDAY = 2;

    /**
     */
    public final static int TUESDAY = 3;

    /**
     */
    public final static int WEDNESDAY = 4;

    /**
     */
    public final static int THURSDAY = 5;

    /**
     */
    public final static int FRIDAY = 6;


    private final static SimpleDateFormat DateTimeFormatter = new SimpleDateFormat(
            "yyyy.MM.dd HH:mm:ss");
    private final static SimpleDateFormat DateFormatter = new SimpleDateFormat(
            "yyyy.MM.dd");


    public final static SimpleDateFormat DefaultDateFormatter = new SimpleDateFormat("yyyy-MM-dd");

    public final static SimpleDateFormat DefaultTimeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final static SimpleDateFormat TimeFormatter = new SimpleDateFormat(
            "HH:mm:ss");
    private final static SimpleDateFormat DateTimeTrimFormatter = new SimpleDateFormat(
            "yyyyMMddHHmmss");
    private final static SimpleDateFormat DateTrimFormatter = new SimpleDateFormat(
            "yyyyMMdd");
    private final static SimpleDateFormat TimeTrimFormatter = new SimpleDateFormat(
            "HHmmss");

    private final static SimpleDateFormat chineseFormatter = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");

    public final static String DATETIME_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
    public final static String DATETIME_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private DateUtil()
    {
    }


    public static String convertDefaultDateString(Date date)
    {
        return DefaultDateFormatter.format(date);
    }

    public static String convertDefaultTimeString(Date date)
    {
        return DefaultTimeFormatter.format(date);
    }

    public static String convertDateTime2String(Date date)
    {
        return DateTimeFormatter.format(date);
    }

    public static String convertDate2String(Date date)
    {
        return DateFormatter.format(date);
    }

    public static String convertTime2String(Date date)
    {
        return TimeFormatter.format(date);
    }

    public static String currentDateTimeString()
    {
        return DateTimeFormatter.format(new Date());
    }

    public static String currentDateTimeStringTrim()
    {
        return DateTimeTrimFormatter.format(new Date());
    }

    public static String currentDateString()
    {
        return DateFormatter.format(new Date());
    }

    public static String currentDateStringTrim()
    {
        return DateTrimFormatter.format(new Date());
    }

    public static String currentTimeString()
    {
        return TimeFormatter.format(new Date());
    }

    public static String currentTimeStringTrim()
    {
        return TimeTrimFormatter.format(new Date());
    }

    public static String convertYear2CYear(String str) throws Exception
    {
        if (str == null || str.trim().length() < 4)
            return str;
        String year = str.substring(0, 4);
        int _year = Integer.parseInt(year);
        _year -= 11;
        return (_year % 100) + str.substring(4);
    }

    /**
     * ************************************************************************
     * 获得当前日期的字符串形式 格式 yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getToday()
    {
        Calendar calendar = Calendar.getInstance();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        StringBuffer bdate = new StringBuffer(formatter.format(calendar
                .getTime()));

        return bdate.toString();
    }

    /**
     * @param date
     * @return
     */
    public static String convertDateToString(Date date)
    {
        return chineseFormatter.format(date);
    }

    /**
     * 处理日期函数
     *
     * @return 字符串 格式为 “yy/mm/dd hh:mm:ss” 例 “2000/10/17 00：00：00”
     * 该返回值可以直接插入到数据库中 类型为 DATE 的字段中
     * @parame 字符串 格式为 “yy/mm/dd” 例“2000/10/17”
     */
    public static String getDate(String sDate)
    {
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");

            Date fromdate = new Date(sDate);

            StringBuffer bdate = new StringBuffer(formatter.format(fromdate));

            return bdate.toString();
        } catch (Exception e)
        {
            // e.printStackTrace();log.error(e.getMessage());

            return sDate;
        }
    }

    // 截取表示时间字符串的指定长度
    public static String subStringDate(String date)
    {

        if (date != null && date.length() > 15)
        {
            return date.substring(0, 16);
        }

        return "";
    }


    /**
     * 获得指定日期到当前时间的年份差
     *
     * @param date 指定格式 “YYYY-MM-DD”
     * @return 如果指定时间大于当前时间返回负整数，否则返回正整数
     */
    public static int getDifferenceFromTodayForYear(String date)
    {

//		if(date==null || date.trim().equals("")) return 0;
//		
//		String now=DateUtil.getDate();
//		
//		String [] temp=StringUtil.toArray(now);
//		
//		int nowYear=Integer.parseInt(temp[0]);
//		
//		temp=StringUtil.toArray(date);
//		
//		int dateYear=Integer.parseInt(temp[0]);
//		
//		return nowYear-dateYear;

        return 0;

    }


    /**
     * ************************************************************************
     * 获得指定时间 于当前时间的 天数差 (当前时间天数 减去 指定时间天数) 如果指定时间比当前时间小 则 返回一个大于0的整数 否则返回一个
     * 小于或等于0 的整数 异常情况下返回 999
     *
     * @param from_date
     * @return
     */
    public static int getDifferenceFromToday(String from_date)
    {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try
        {
            Date from_date_d = sdf.parse(from_date);

            Calendar calendar = Calendar.getInstance();
            Date to_day = calendar.getTime();

            calendar.setTime(from_date_d);

            int from_day = calendar.get(Calendar.DAY_OF_YEAR);

            calendar.setTime(to_day);

            int to_day_int = calendar.get(Calendar.DAY_OF_YEAR);


            return to_day_int - from_day;

        } catch (ParseException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error(e.getMessage());

        }

        return 999;
    }

    // 获得2个日期的时间差
    public static int getDifferenceFromDate(String from_date, String to_date)
    {

        try
        {


            Calendar calendar = Calendar.getInstance();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date from_date_d = sdf.parse(from_date);

            Date to_date_d = sdf.parse(to_date);

            calendar.setTime(from_date_d);

            int from_day = calendar.get(Calendar.DAY_OF_YEAR);


            calendar.setTime(to_date_d);

            int to_day = calendar.get(Calendar.DAY_OF_YEAR);


            return to_day - from_day;
        } catch (Exception e)
        {
            e.toString();

        }

        return 999;
    }

    /**
     * ************************************************************************
     * 将string 转换成 calendar
     *
     * @param date
     * @return
     */
    public static Calendar getCalendarFormString(String date)
    {
        Calendar temp = Calendar.getInstance();

        Date temp_date = getDateFormString(date);

        temp.setTime(temp_date);

        return temp;
    }

    /**
     * ************************************************************************
     * 将 string 转换成 java.util.date
     *
     * @param date
     * @return
     */
    public static Date getDateFormString(String date)
    {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date temp_date = null;
        try
        {
            temp_date = formatter.parse(date);
        } catch (ParseException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error(e.getMessage());

        }

        return temp_date;
    }

    /**
     * ************************************************************************
     * 判断 一个时间 是否在 标志时间之前 如果比标志时间小 返回 true 否则返回 false
     *
     * @param order_date
     * @param tag_date
     * @return
     */
    public static boolean ifbefore(String order_date, String tag_date)
    {
        boolean temp = true;

        Calendar order_date_calendar = getCalendarFormString(order_date);

        Calendar tag_date_calendar = getCalendarFormString(tag_date);

        // 如果 时间 在标志时间之前
        if (order_date_calendar.before(tag_date_calendar))
        {
            temp = true;
        } else
        {
            temp = false;
        }

        return temp;
    }

    /**
     * ************************************************************************
     * 获得当前系统时间 并转换成字符串 格式 yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getDate()
    {
        Calendar calendar = Calendar.getInstance();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        StringBuffer bdate = new StringBuffer(formatter.format(calendar
                .getTime()));

        return bdate.toString();

    }

    /**
     * ************************************************************************
     * 返回系统当前时间 之后的指定天数的 时间， 格式为 "yyyy-MM-dd HH:mm:ss"
     *
     * @param days
     * @return
     */
    public static String getAfterDate(int days)
    {
        Calendar calend = Calendar.getInstance(); // 获得当前日期

        calend.add(Calendar.DAY_OF_MONTH, days); // 在当前日期上+7天

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        StringBuffer bdate = new StringBuffer(formatter
                .format(calend.getTime()));

        return bdate.toString();
    }

    /**
     * @return
     */
    public static String getCurrentDate()
    {
        Calendar calendar = Calendar.getInstance();
        int tYear = calendar.get(Calendar.YEAR);
        int tMonth = calendar.get(Calendar.MONTH) + 1;
        int tDate = calendar.get(Calendar.DATE);
        return String.valueOf(tYear * 10000 + tMonth * 100 + tDate);
    }

    /**
     * ************************************************************************
     * 取得日期前后N月的日期
     *
     * @param date(format: yyyyMMdd)
     * @param i            (第N日,正数表示后几月，负数表示前几月)
     * @author nilomiao
     * ************************************************************************
     */
    public static String getNMonth(String date, int i)
    {
        String result = "";
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

            if (date.length() == 8)
            {
                formatter = new SimpleDateFormat("yyyyMMdd");
            } else if (date.length() == 6)
            {
                formatter = new SimpleDateFormat("yyyyMM");
            }

            Date theDate = formatter.parse(date);

            theDate.setMonth(theDate.getMonth() + i);
            result = formatter.format(theDate);

        } catch (ParseException e)
        {
            e.printStackTrace();
            log.error(e.getMessage());

        }

        return result;

    }


    public static String getNMonth1(String date, int i)
    {
        String result = "";
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            if (date.length() == 10)
            {
                formatter = new SimpleDateFormat("yyyy-MM-dd");
            } else if (date.length() == 7)
            {
                formatter = new SimpleDateFormat("yyyy-MM");
            }

            Date theDate = formatter.parse(date);

            theDate.setMonth(theDate.getMonth() + i);
            result = formatter.format(theDate);

        } catch (ParseException e)
        {
            e.printStackTrace();
            log.error(e.getMessage());

        }

        return result;
    }


    /**
     * ************************************************************************
     * 取得日期前后N日的日期
     *
     * @param date(format: yyyyMMdd)
     * @param i            (第N日,正数表示后几日，负数表示前几日)
     * @author nilomiao
     * ************************************************************************
     */
    public static String getNDay(String date, int i)
    {
        String result = "";
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

            if (date.length() == 8)
            {
                formatter = new SimpleDateFormat("yyyyMMdd");
            }

            Date theDate = formatter.parse(date);
            theDate.setDate(theDate.getDate() + i);
            result = formatter.format(theDate);
        } catch (ParseException e)
        {
            e.printStackTrace();
            log.error(e.getMessage());

        }
        return result;
    }

    public static String getBeforeDay(String date, int i)
    {
        String result = "";
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

            Date theDate = formatter.parse(date);
            theDate.setDate(theDate.getDate() - i);
            result = formatter.format(theDate);
        } catch (ParseException e)
        {
            e.printStackTrace();
            log.error(e.getMessage());

        }
        return result;
    }

    public static String getAfterDay(String date, int i)
    {
        String result = "";
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

            Date theDate = formatter.parse(date);
            theDate.setDate(theDate.getDate() + i);
            result = formatter.format(theDate);
        } catch (ParseException e)
        {
            e.printStackTrace();
            log.error(e.getMessage());

        }
        return result;
    }

    /**
     * ************************************************************************
     * 取得日期前后N小时的日期
     *
     * @param date（格式为20050101）
     * @param i                 (第N日,正数表示后几小时，负数表示前几小时)
     * @author nilomiao
     * ************************************************************************
     */
    public static String getNHour(String date, int i)
    {
        String result = "";
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

            if (date.length() == 10)
            {
                formatter = new SimpleDateFormat("yyyyMMddHH");
            }

            Date theDate = formatter.parse(date);
            theDate.setHours(theDate.getHours() + i);
            result = formatter.format(theDate);

        } catch (ParseException e)
        {
            e.printStackTrace();
            log.error(e.getMessage());

        }
        return result;
    }

    /**
     * ************************************************************************
     * 从开始时间计时,算出到目前为止还剩时间
     *
     * @param continualDays
     * @return 剩余时间 x天x小时x分钟x秒
     * @author nilomiao
     * ************************************************************************
     */
    public static String countDown(String startDateStr, float continualDays)
    {
        String result = "";
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .parse(startDateStr);
            Date nowDate = new Date();

            long cutLong = (long) (24F * 3600F * 1000F * continualDays);
            long useLong = nowDate.getTime() - startDate.getTime();

            Date rawDate = formatter.parse("0000-00-00 00:00:00");
            rawDate.setTime(rawDate.getTime() + cutLong - useLong);

            result = rawDate.getDay() + "天" + rawDate.getHours() + "小时"
                    + rawDate.getMinutes() + "分钟" + rawDate.getSeconds() + "秒";

        } catch (Exception e)
        {
            e.printStackTrace();
            log.error(e.getMessage());

        }

        return result;
    }

    /**
     * ************************************************************************
     * 转换日期格式
     *
     * @param strDate
     * @return String YYYYMMDD,YYYYMMDDHHMMSS
     * ************************************************************************
     */
    public static String getSimpleFormat(String strDate)
    {
        if (strDate.length() == 10)
        {
            return strDate.substring(0, 4) + strDate.substring(5, 7)
                    + strDate.substring(8, 10);

        } else if (strDate.length() >= 19)
        {
            return strDate.substring(0, 4) + strDate.substring(5, 7)
                    + strDate.substring(8, 10) + strDate.substring(11, 13)
                    + strDate.substring(14, 16) + strDate.substring(17, 19);

        } else
        {
            return null;
        }
    }

    /**
     * ************************************************************************
     * 转换日期格式
     *
     * @param strDate
     * @return String (YYYY/MM/DD,YYYY-MM-DD,YYYY/MM/DD
     * HH:MM:SS, YYYY-MM-DD HH:MM:SS)
     * ************************************************************************
     */
    public static String getFullFormat(String strDate)
    {
        if (strDate.length() == 8)
        {
            return strDate.substring(0, 4) + "/" + strDate.substring(4, 6)
                    + "/" + strDate.substring(6, 8);

        } else if (strDate.length() >= 14)
        {
            return strDate.substring(0, 4) + "/" + strDate.substring(4, 6)
                    + "/" + strDate.substring(6, 8) + " " + strDate.substring(8, 10)
                    + ":" + strDate.substring(10, 12) + ":" + strDate.substring(12, 14);

        } else
        {
            return "";
        }
    }


    /**
     * *
     * 时间格式转换
     *
     * @param strDate 格式：yyyy/MM/dd HH:mm:ss
     * @return 格式：yyyy-MM-dd HH:mm:ss
     * @author robert  Aug 11, 2008
     */
    public static String changeDateFormat(String strDate)
    {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        SimpleDateFormat formatter_temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try
        {
            Date temp_date = formatter.parse(strDate);

            StringBuffer bdate = new StringBuffer(formatter_temp.format(temp_date));

            return bdate.toString();


        } catch (ParseException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        return "";
    }

    /**
     * 获得当前日期
     *
     * @return 格式："yyyy-MM-dd"
     */
    public static String getSimpleCurrentDate()
    {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date());
    }

    /**
     * 验证时间是否过期
     *
     * @param createKeyDate
     * @param expire_time
     * @return
     */
    public static boolean isValidKey(String createKeyDate, long expire_time)
    {
        SimpleDateFormat dateformat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        // 当前时间
        Date now = new Date();
        try
        {
            Date createTime = dateformat.parse(createKeyDate);
            Date currentTime = dateformat.parse(dateformat.format(now));
            long time = (currentTime.getTime() - createTime.getTime()) / 1000;
            return time > expire_time ? true : false;
        } catch (ParseException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error(e.getMessage());

        }
        return false;
    }

    /**
     * 以友好的方式显示时间
     *
     * @param sdate
     * @return
     */
    public static String friendly_time(String sdate)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ftime = "";
        try
        {
            Date time = sdf.parse(sdate);
            if (time == null)
            {
                return "Unknown";
            }

            Calendar cal = Calendar.getInstance();

            //判断是否是同一天
            String curDate = sdf.format(cal.getTime());
            String paramDate = sdf.format(time);
            if (curDate.equals(paramDate))
            {
                int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
                if (hour == 0)
                    ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
                else
                    ftime = hour + "小时前";
                return ftime;
            }

            long lt = time.getTime() / 86400000;
            long ct = cal.getTimeInMillis() / 86400000;
            int days = (int) (ct - lt);
            if (days == 0)
            {
                int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
                if (hour == 0)
                    ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
                else
                    ftime = hour + "小时前";
            } else if (days == 1)
            {
                ftime = "昨天";
            } else if (days == 2)
            {
                ftime = "前天";
            } else if (days > 2 && days <= 10)
            {
                ftime = days + "天前";
            } else if (days > 10)
            {
                ftime = DefaultTimeFormatter.format(time);
            }

        } catch (ParseException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error(e.getMessage());
            return ftime;
        }
        return ftime;
    }

    public static String getBirthFromCardNO(String icard)
    {
        int len = icard.length();
        StringBuilder ymd = new StringBuilder();
        switch (len)
        {
            case 15:
                ymd.append("19").append(icard.substring(6, 12));
                break;
            case 18:
                ymd.append(icard.substring(6, 14));
                break;
            default:
                return "2010-01-01";
        }
        return ymd.substring(0, 4) + "-" + ymd.substring(4, 6) + "-" + ymd.substring(6, 8);
    }

    /**
     * 计算年龄
     * @param birthday
     * @return
     */
    public static int getAgeByBirthday(Date birthday)
    {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthday))
        {
            throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(birthday);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth)
        {
            if (monthNow == monthBirth)
            {
                // monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth)
                {
                    age--;
                }
            } else
            {
                // monthNow>monthBirth
                age--;
            }
        }
        return age;
    }

    /**
     * 将代表日期的字符串分割为代表年月日的整形数组
     *
     * @param date
     * @return
     */
    public static int[] splitYMD(String date)
    {
        date = date.replace("-", "");
        int[] ymd = {
                0, 0, 0
        };
        ymd[Y] = Integer.parseInt(date.substring(0, 4));
        ymd[M] = Integer.parseInt(date.substring(4, 6));
        ymd[D] = Integer.parseInt(date.substring(6, 8));
        return ymd;
    }

    /**
     * 检查传入的参数代表的年份是否为闰年
     *
     * @param year
     * @return
     */
    public static boolean isLeapYear(int year)
    {
        return year >= gregorianCutoverYear ? ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)))
                : (year % 4 == 0);
    }

    /**
     * 日期加1天
     *
     * @param year
     * @param month
     * @param day
     * @return
     */
    private static int[] addOneDay(int year, int month, int day)
    {
        if (isLeapYear(year))
        {
            day++;
            if (day > DAYS_P_MONTH_LY[month - 1])
            {
                month++;
                if (month > 12)
                {
                    year++;
                    month = 1;
                }
                day = 1;
            }
        } else
        {
            day++;
            if (day > DAYS_P_MONTH_CY[month - 1])
            {
                month++;
                if (month > 12)
                {
                    year++;
                    month = 1;
                }
                day = 1;
            }
        }
        int[] ymd = {
                year, month, day
        };
        return ymd;
    }

    /**
     * 将不足两位的月份或日期补足为两位
     *
     * @param decimal
     * @return
     */
    public static String formatMonthDay(int decimal)
    {
        DecimalFormat df = new DecimalFormat("00");
        return df.format(decimal);
    }

    /**
     * 将不足四位的年份补足为四位
     *
     * @param decimal
     * @return
     */
    public static String formatYear(int decimal)
    {
        DecimalFormat df = new DecimalFormat("0000");
        return df.format(decimal);
    }

    /**
     * 计算两个日期之间相隔的天数
     *
     * @param begin
     * @param end
     * @return
     * @throws ParseException
     */
    public static long countDay(String begin, String end)
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date beginDate, endDate;
        long day = 0;
        try
        {
            beginDate = format.parse(begin);
            endDate = format.parse(end);
            day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
        } catch (ParseException e)
        {
            e.printStackTrace();
            log.error(e.getMessage());

        }
        return day;
    }

    /**
     * 计算两个日期之间相隔的天数
     *
     * @param begin
     * @param end   format
     * @return
     * @throws ParseException
     */
    public static long countDay(String begin, String end, SimpleDateFormat format)
    {
        Date beginDate, endDate;
        long day = 0;
        try
        {
            beginDate = format.parse(begin);
            endDate = format.parse(end);
            day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
        } catch (ParseException e)
        {
            e.printStackTrace();
            log.error(e.getMessage());

        }
        return day;
    }
    /**
     * 计算两个日期之间相隔的天数
     *
     * @param beginDate
     * @param endDate
     * @return
     */
    public static long countDay(Date beginDate, Date endDate)
    {
        long day = 0;
        try
        {
            day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
        } catch (Exception e)
        {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return day;
    }
    /**
     * 以循环的方式计算日期
     *
     * @param beginDate endDate
     * @param endDate
     * @return
     */
    public static List<String> getEveryday(String beginDate, String endDate)
    {
        long days = countDay(beginDate, endDate);
        int[] ymd = splitYMD(beginDate);
        List<String> everyDays = new ArrayList<String>();
        everyDays.add(beginDate);
        for (int i = 0; i < days; i++)
        {
            ymd = addOneDay(ymd[Y], ymd[M], ymd[D]);
            everyDays.add(formatYear(ymd[Y]) + "-" + formatMonthDay(ymd[M])
                    + "-" + formatMonthDay(ymd[D]));
        }
        return everyDays;
    }

    /**
     * 计算当前日期是周几
     *
     * @param date
     * @return
     */
    public static Integer week(Date date)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int day = cal.get(Calendar.DAY_OF_WEEK);
        if (day == Calendar.SATURDAY)
            return 6;
        else if (day == Calendar.SUNDAY)
            return 7;//0
        else if (day == Calendar.MONDAY)
            return 1;
        else if (day == Calendar.TUESDAY)
            return 2;
        else if (day == Calendar.WEDNESDAY)
            return 3;
        else if (day == Calendar.THURSDAY)
            return 4;
        else if (day == Calendar.FRIDAY)
            return 5;
        else
        {
            return -999;
        }
    }

    /**
     * 两日期间的分钟数
     *
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return 像个分钟数
     */
    public static int countMinutes(String startDate, String endDate)
    {
        try {
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date d1 = sim.parse(startDate);
            Date d2 = sim.parse(endDate);
            return (int) ((d2.getTime() - d1.getTime()) / (60 * 1000));
        } catch (Exception e) {
            try
            {
                throw e;
            } catch (ParseException e1)
            {
                e1.printStackTrace();
            }
        }
        return -10;
    }


    //检查当前日期是不是本月最后一天
    private Date lastDayOfMonth(Date date)
    {

        //检查当前日期是不是本月最后一天，若是的话则生成月份报表
//        Calendar calendar = Calendar.getInstance();
//        //calendar.add(Calendar.DATE, -1);// 日期加1
//        String day = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
//        Date date = new SimpleDateFormat("yyyy-MM-dd").parse(day);
//        date = lastDayOfMonth(date);
//        String lastDay = (new SimpleDateFormat("yyyy-MM-dd").format(date));
//        if(lastDay.equals(day))
//        {
//            createReportXLS.createMonthBaseInfoXLS(ddr.getDep(),reportBaseInfo,new SimpleDateFormat("yyyy-MM").format(calendar.getTime()));
//        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.roll(Calendar.DAY_OF_MONTH, -1);
        return cal.getTime();
    }

    //计算两日期间相间分钟数
    public static int countMinutes2(String startDate, String endDate)
    {
        Long result = 0l;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date d1 = sdf.parse(startDate);
            Date d2 = sdf.parse(endDate);

            result = ((d2.getTime() - d1.getTime()) / (60 * 1000));

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result.intValue();
    }

    //计算两日期间相间分钟数
    public static int countMinutes(Date startDate, Date endDate) throws Exception
    {
        int val = (int) ((endDate.getTime() - startDate.getTime()) / (60 * 1000));
        return val;
    }

    /**
     * 判断两个时间段是否有重叠
     *
     * @param beginDate1 时间段1 开始时间
     * @param endDate1   时间段1 结束时间
     * @param beginDate2 时间段2 开始时间
     * @param endDate2   时间段2 结束时间
     * @param dateformat 时间格式
     * @return true 存在重叠
     * false 不重叠
     */

    public static Boolean isOverLaps(String beginDate1, String endDate1, String beginDate2, String endDate2, String dateformat)
    {
        try
        {
            SimpleDateFormat sdf = new SimpleDateFormat(dateformat);
            Date date1b = sdf.parse(beginDate1);
            Date date1e = sdf.parse(endDate1);
            Date date2b = sdf.parse(beginDate2);
            Date date2e = sdf.parse(endDate2);

            if (date2b.compareTo(date1e) * date2e.compareTo(date1b) > 0)
                return false;
            else
            {//判断是否是时间交接点:08:00-12:00 12:00-15:00
                if (date2b.equals(date1e) || date2e.equals(date1b))
                {
                    return false;
                } else return true;
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    public static Date str2Date(String date,String dateFormat){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            return sdf.parse(date);
        } catch (Exception e) {
            try
            {
                throw e;
            } catch (ParseException e1)
            {
                e1.printStackTrace();
                return null;
            }
        }
    }

    public static String date2Str(Date date,String dateFormat){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            return sdf.format(date);
        } catch (Exception e) {
            throw e;
        }
    }

    public static void main(String[] args)
    {
        try
        {
//            List<String> list = getEveryday("2013-11-22", "2013-12-05");
//            SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            for (String result : list)
//            {
//                System.out.println(result + "--------->" + week(sdfDateFormat.parse(result)));
//            }
//            //2014-06-11 10:15----startCount----->2014-06-11 10:22:01=========>622
//            System.out.println(countMinutes("2014-06-11 10:15", "2014-06-11 10:22:01"));

            String card = "330419198002210831";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            int age = DateUtil.getAgeByBirthday(sdf.parse(DateUtil.getBirthFromCardNO(card)));
            System.out.println(age);
        } catch (Exception e)
        {
            e.printStackTrace();
            log.error(e.getMessage());

        }
    }
}
